package com.cqvie.daoTest;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

import com.cqvie.dao.CommonDao;
import com.cqvie.dao.UserDao;
import com.cqvie.model.Permission;
import com.cqvie.model.Role;
import com.cqvie.model.User;
import com.cqvie.model.UserRole;
import com.cqvie.tools.ClassScanner;

@ContextConfiguration(locations = {"classpath:spring.xml","classpath:spring-hibernate.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
// defaultRollback=true不会改变数据库，false会改变数据库
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
@Transactional
public class InsertInitData {

    @Resource
    private CommonDao commonDao;
    
    @Resource 
    private UserDao dao;
    
    @Test
    public void insertPermission_URL(){
    	
    	Map<String, String> map=ClassScanner.getMethods();
    	
    	for (Entry<String, String> entry : map.entrySet()) { 
    		Permission object=new Permission();
    		object.setDescription(entry.getValue());
    		object.setMethod(entry.getKey());
    		commonDao.addObject(object);
    		System.out.println("insert success");
		} 
    }
    
    @Test
    public void insertRole(){
    	Role role= new Role();
    	role.setDescription("administrators");
    	role.setName("admins");
    	role.setRoles(new HashSet(commonDao.findAllByHQL("FROM Permission")));
    	commonDao.addObject(role);
    	System.out.println("success");
    }
	
//    
    @Test
    public void insertUser(){
    	User user=new User();
    	user.setId("das56d4as5d4as4da56sd4a65");
    	user.setCreateDate(new Date());
    	user.setIsDelete(0);
    	user.setUsername("123");
    	user.setPassword("abc");
    	System.out.println("insert into User : "+dao.add(user));
    	UserRole role= new  UserRole();
    	role.setRole((Role) commonDao.findObjectByHQL("FROM Role where id=1"));
    	role.setUser((User) commonDao.findObjectByHQL("FROM User where id=?",new Object[]{user.getId()}));
    	System.out.println("insert into role : "+commonDao.addObject(role));
    	List<UserRole> list=new ArrayList<>();
    	list.add(role);
    	user.setUserRoles(list);
    	commonDao.updateObjectByHQL("update User user set user.userRoles=?",new Object[] { list});
    	System.out.println("true");
    	
    }
}
